package com.blockmeta.bbs.immodule.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.eventbus.IMMsgCountEvent;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.ImSessionListAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.utils.NotificationHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import butterknife.BindView;

/**
 * Created by author on 2019/1/23.
 * <p>
 * <p>
 * 聊天列表页面只需要绑定广播就可以了！
 * 不需要建立Socket通信！
 */
@Route(path = RouterPath.IM_PERSONAL_MSG_FRAGMENT)
public class IMPersonalMsgFragment extends IMBaseFragment {
    @BindView(R2.id.list_recy)
    RecyclerView mListRecy;
    /**
     * 当前用户数据
     */
    private ImSessionListAdapter mAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        mContext = getActivity();
        EventBus.getDefault().register(this);
        IMApplicationContext.getIMMetaService().register(this);
        return LayoutInflater.from(mContext).inflate(R.layout.fragment_im_main, null);
    }


    @Override
    public void initView() {
        initAdapter();
        refreshData();
        NotificationHelper.getInstance(mContext).clearNotifyIds();
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d("xiao" + "imsessionlistfragemnt onresume");
    }


    @Override
    public void onPause() {
        super.onPause();
        LogUtils.d("xiao" + "imsessionlistfragemnt onpause");
    }

    /**
     * 初始化Adapter
     * 由于每一天消息都在数据库中是一行，所以在构建数据之前需要先对数据库里面的数据进行合并，把相同会话合并成一个列表
     * 然后传入到适配器中进行处理
     */
    private void initAdapter() {
        mListRecy.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new ImSessionListAdapter(null, mContext);
        ((SimpleItemAnimator) mListRecy.getItemAnimator()).setSupportsChangeAnimations(false);
        mListRecy.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<ChatMessage> data = mAdapter.getData();
                ChatMessage cm = data.get(position);
                int i = view.getId();
                if (i == R.id.btn_top) {
                    if (IMApplicationContext.getChatMessageDomainService().isMessageStick(cm)) {
                        ToastUtil.show("取消置顶");
                        IMApplicationContext.getChatMessageDomainService().updateChatMessageStick(cm.getId(), false);
                    } else {
                        ToastUtil.show("置顶");
                        IMApplicationContext.getChatMessageDomainService().updateChatMessageStick(cm.getId(), true);
                    }
                    refreshData();

                } else if (i == R.id.btn_unread) {
                    ToastUtil.show("设置成已读");
                    IMApplicationContext.getChatMessageDomainService().updateChatMessageReaded(cm.getId(), true);
                    refreshData();

                } else if (i == R.id.btn_delete) {
                    IMApplicationContext.getChatMessageDomainService().deleteListChatMessage(AccountHelper.getUidInt()
                            , cm);
                    mAdapter.remove(position);
                    ToastUtil.show("删除");
                }
            }
        });

        View view = mAdapter.getEmptyView();
        if (view == null) {
            View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_login, null);
            Button btnAddCircle = emptyView.findViewById(R.id.btn_addcircle);
            btnAddCircle.setVisibility(View.GONE);
            btnAddCircle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Log.d("flutterting", "openselectpage");
                    Log.d("flutterting", "openselectpage");
                    ThrioNavigator.push("/home/select",
                            "test",
                            false,
                            (view) -> {
                                return null;
                            }
                    );
                }
            });
            Button joinCircle = emptyView.findViewById(R.id.btn_joincircle);
            joinCircle.setVisibility(View.GONE);
            joinCircle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("flutterting", "openselectpage");
                    ThrioNavigator.push("/activity/deployList",
                            "test",
                            false,
                            (view) -> {
                                return null;
                            }
                    );
                }
            });
            mAdapter.setEmptyView(emptyView);
        }
    }

    //收到在线消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_IMMessage onLineMessage) {
        //暂时不接受人人消息
        if(onLineMessage.m_message.getMsgType() == ChatMessage.MSG_TYPE_UCG){
            return;
        }
        IMApplicationContext.getChatMessageDomainService().notifyMsgListViewChange(mAdapter, onLineMessage.m_message);
    }


    //发送消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_SendIMMessage event) {
        IMApplicationContext.getChatMessageDomainService().notifyMsgListViewChange(mAdapter, event.chatMessage);
    }

    //收到已读某用户的消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_ReadAllMsgFromOne event) {
        LogUtils.i("author" + "BaseChatActivitu");
        IMApplicationContext.getChatMessageDomainService().notifyMsgListViewUserReaded(mAdapter, event.toUserId, event.type);
    }

    //收到群置顶消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_CircleStickUpdate event) {
        LogUtils.i("author" + "BaseChatActivitu");
        refreshData();
    }





    private void refreshData() {
        List<ChatMessage> data2 = IMApplicationContext.getChatMessageDomainService().getPersonalTalkListMessage(
                AccountHelper.getUidInt());
        if (mAdapter != null) {
            mAdapter.setNewData(data2);
        }

    }

    //接收到离线消息！
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveOutLineMessage(IMMetaBase.Event_IMMessageList outLineMessageList) {
        refreshData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void loginUI(MsgSuccess msgSuccess) {
        if (msgSuccess.msg.equals("LOGIN") && !AccountHelper.isLogin()) {
            //退出登陆
            mAdapter.setNewData(null);
            EventBus.getDefault().post(IMMsgCountEvent.getInstance().setMsgCount(0));
        } else if (msgSuccess.msg.equals("LOGIN") && AccountHelper.isLogin()) {
            refreshData();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommentEvent(IMMetaBase.Event_Comment_Data eventCode) {
        if (eventCode.eventCode == Params.IMEvent_Quit_Circle) {
            //退出圈子
            //刷新页面，清除数据！
            refreshData();
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        IMApplicationContext.getIMMetaService().unregister(this);
        super.onDestroyView();
    }
}
